package com.aispeech.rcprvd.provider.base;

import android.app.Application;
import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import com.aispeech.rcprvd.jni.RcNativeProcessJni;
import com.aispeech.rcprvd.utils.RcPrvdConst;

import no.nordicsemi.android.ble.livedata.ObservableBleManager;

public abstract class GattServerDataProvider implements IDataProvider {
    private final String TAG = "GattServerDataProvider";
    private HandlerThread mReadThread;
    private Handler mHandler;
    //    private ObservableBleManager mJJBleManager;
    private BluetoothDevice mTargetDevice;

    protected abstract BluetoothDevice getTargetDevice();

    protected abstract int getNativeProcessId();

    protected abstract ObservableBleManager getTargetBleManager();


    public GattServerDataProvider(Application context) {
        mReadThread = new HandlerThread("GST");//gatt service read thread
        mReadThread.start();
        mHandler = new Handler(mReadThread.getLooper());
    }


    private Runnable mGattReadRunnable = new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "GattReadRunnable start: ---------------");

            if (mTargetDevice != null && null != getTargetBleManager()) {
                Log.d(TAG, "GattReadRunnable: getTargetBleManager connect ------ ");
                getTargetBleManager().connect(mTargetDevice)
                        .retry(3, 100)
                        .useAutoConnect(false)
                        .enqueue();
            } else {
                Log.e(TAG, "run: mTargetDevice is null");
                return;
            }

            Log.d(TAG, "GattReadRunnable over: ---------------");
        }
    };


    @Override
    public int start() {
        Log.d(TAG, "start: ");
        //step 1: get target device
        mTargetDevice = getTargetDevice();
        if (mTargetDevice == null) {
            Log.e(TAG, "start: NO_DEVICE_FOUND");
            return RcPrvdConst.ErrorCode.NO_DEVICE_FOUND;
        }

        int ret = RcNativeProcessJni.native_process_start(getNativeProcessId());
        if (ret != RcPrvdConst.ErrorCode.NO_ERROR) {
            Log.e(TAG, "GattReadRunnable err : " + ret);
            return RcPrvdConst.ErrorCode.NATIVE_ERR;
        }

        mHandler.post(mGattReadRunnable);
        return RcPrvdConst.ErrorCode.NO_ERROR;
    }

    @Override
    public int stop() {
        Log.d(TAG, "stop: ");
        int ret = RcNativeProcessJni.native_process_stop(RcPrvdConst.RCDevSource.JINJU_BLE_GATT);
        if (ret < 0) {
            Log.e(TAG, "native_process_stop err : " + ret);
            return RcPrvdConst.ErrorCode.NATIVE_ERR;
        }
        return RcPrvdConst.ErrorCode.NO_ERROR;
    }
}
